package com.sunyur.tailor.channel.web.outer.materiel.controller;

import com.alibaba.fastjson.JSON;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.base.ValidList;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.service.inner.materiel.param.BatchAdditionMaterielParam;
import com.sunyur.tailor.channel.service.inner.materiel.service.SunyurMaterielService;
import com.sunyur.tailor.channel.web.outer.materiel.dto.BatchAdditionMaterielDTO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author pengbing
 * @Description //物料控制层
 * @Date 16:13 2021/12/30
 * @Param
 * @return
 **/
@Log4j2
@RestController
@RequestMapping("/outer/materiel")
public class MaterielController {
    /**
     * 物料服务
     */
    @Autowired
    private SunyurMaterielService sunyurMaterielService;

    /**
     * 新增物料
     * @param
     * @return
     */
    @PostMapping(value = "/batchCreate", produces = MediaType.APPLICATION_JSON_VALUE)
    public ChannelResult batchCreate(@RequestBody @Valid ValidList<BatchAdditionMaterielDTO> batchAdditionMaterielDTO) {
        log.info("MaterielController batchCreate param:{}", JSON.toJSONString(batchAdditionMaterielDTO));
        ChannelResult result = new ChannelResult<>();
        if (CollectionUtils.isEmpty(batchAdditionMaterielDTO)) {
            log.error("MaterielController batchCreate param is null");
            result.setError(MiddleResultEnum.PARAM_NULL.getCode(), MiddleResultEnum.PARAM_NULL.getValue());
            return result;
        }
        try {
            List<BatchAdditionMaterielParam> batchAdditionMaterielParamList = getBatchAdditionMaterielParams(batchAdditionMaterielDTO);
            result = sunyurMaterielService.batchAdditionMateriel(batchAdditionMaterielParamList);
        } catch (Exception e) {
            log.error("MaterielController batchCreate exception:{}", e);
            result.setError(MiddleResultEnum.EXCEPTION.getCode(), MiddleResultEnum.EXCEPTION.getValue());
        }
        return result;
    }

    private List<BatchAdditionMaterielParam> getBatchAdditionMaterielParams(List<BatchAdditionMaterielDTO> batchAdditionMaterielDTO) {
        List<BatchAdditionMaterielParam> batchAdditionMaterielParamList=new ArrayList<>();
        batchAdditionMaterielDTO.forEach(items -> {
            BatchAdditionMaterielParam target = new BatchAdditionMaterielParam();
            BeanUtils.copyProperties(items, target);
            batchAdditionMaterielParamList.add(target);
        });
        return batchAdditionMaterielParamList;
    }
}
